

cc.Class({
    extends: cc.Component,
    mixins: [cc.EventTarget],

    properties: {
        folder: 'prefab'
    },

    ctor() {
        this.list = [];
        this._curWindowIdx = 0;
    },

    open(prefabName, callback) {
        cc.loader.loadRes(this.folder +'/'+ prefabName, (err, prefab) => {
            if (err) {
                cc.error(`Load prefab error: ${err}`);
                return;
            }

            let windowNode = cc.instantiate(prefab);

            game.windowManager.addWindow(windowNode);

            this.emit('open', windowNode);

            callback && callback(windowNode);
        });
    },

    addWindow(node) {
        let windowNode = this.getCurrentWindow();
        if (windowNode) windowNode.active = false;

        let scene = cc.director.getScene();
        scene.getComponentInChildren(cc.Canvas).node.addChild(node);

        node.zIndex = 1;

        // Override `destroy` to remove window
        node.destroy = function () {
            game.windowManager.removeWindow(this);
            this.constructor.prototype.destroy.call(this);
        };

        this.list.push(node);

        this._curWindowIdx = this.list.length - 1;
    },
    removeWindow(node) {
        this.list.find((windowNode, idx) => {
            if (windowNode === node) {
                this.list.splice(idx, 1);

                if (idx == this._curWindowIdx) {
                    this._curWindowIdx--;

                    let windowNode = this.getCurrentWindow();
                    if (windowNode) windowNode.active = true;
                }

                return true;
            }
        });
    },
    clearWindows() {
        for (let node of this.list) {
            node.destroy();
        }
    },

    getCurrentWindow() {
        return this.list[this._curWindowIdx];
    },
    getWindow(nodeName) {
        return this.list.find(windowNode => windowNode.name == nodeName);
    },

    tapToOpen(event, data) {
        this.open(data);
    }
});

cc.director.on(cc.Director.EVENT_BEFORE_SCENE_LOADING, (event) => {
    game.windowManager.clearWindows();
});